package com.chinapost.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.po.Tdqlkt;
import com.chinapost.service.DqlktServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Dqlkt;

@Service("dqlktService")
public class DqlktServiceImpl implements DqlktServiceI {

	@Autowired
	private BaseDaoI<Tdqlkt> dqlktDao;


	@Override
	public DataGrid datagrid(Dqlkt dqlkt) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(dqlkt)));
		dg.setTotal(total(dqlkt));
		return dg;
	}

	private Long total(Dqlkt dqlkt) {
		String hql = "select count(*) from Tdqlkt t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqlkt, hql, params);
		return dqlktDao.count(hql, params);
	}

	private List<Tdqlkt> find(Dqlkt dqlkt) {
		String hql = "from Tdqlkt t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqlkt, hql, params);
		if (dqlkt.getOrder() != null && dqlkt.getSort() != null) {
			hql += " order by " + dqlkt.getSort() + " " + dqlkt.getOrder();
		}
		return dqlktDao.find(hql, params, dqlkt.getPage(), dqlkt.getRows());
	}

	private List<Dqlkt> listRows(List<Tdqlkt> lt) {
		List<Dqlkt> rows = new ArrayList<Dqlkt>();
		if (lt != null && lt.size() > 0) {
			for (Tdqlkt t : lt) {
				Dqlkt sub = new Dqlkt();
				BeanUtils.copyProperties(t, sub);
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Dqlkt dqlkt, String hql, Map<String, Object> params) {
		if (dqlkt != null && dqlkt.getCkh() != null && !dqlkt.getCkh().trim().equals("")) {
			hql += " and t.ckh like :kh ";
			params.put("kh", "%%" + dqlkt.getCkh() + "%%");
		}
		return hql;
	}

	

}
